package com.gitee.huanminabc.utils_tools.web_base.utils;


import com.gitee.huanminabc.jcommon.exception.BizException;
import com.gitee.huanminabc.jcommon.file.FileWriterUtil;
import com.gitee.huanminabc.jcommon.file.ZipFileUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Base64;
import java.util.List;

/**
 * web游览器下载指定服务器上的文件
 */
public class FileWebDownLoad {

    //文件下载给游览器
    public static void download(String filePath) {
        HttpServletResponse response = WebContextUtil.getResponse();
        File file = new File(filePath);
        try (
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                InputStream fis = new BufferedInputStream(new FileInputStream(file));
        ) {
            // 以流的形式下载文件。
            byte[] buffer = new byte[fis.available()];
            // 取得文件名。
            String filename = file.getName();
            fis.read(buffer);
            // 设置response的Header
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), StandardCharsets.UTF_8));
            toClient.write(buffer);
        } catch (IOException ex) {
            throw new BizException(ex, "文件下载失败");
        }
    }

    //将下载的文件转换成base64字符串
    public static String downloadToBase64(String filePath) {
        File file = new File(filePath);
        try (
                InputStream fis = new BufferedInputStream(Files.newInputStream(file.toPath()));
        ) {
            // 以流的形式下载文件。
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            return Base64.getEncoder().encodeToString(buffer);
        } catch (IOException ex) {
            throw new BizException(ex, "文件下载失败");
        }
    }


    /**
     * 将所有需要下载的文件以压缩包形式返回给游览器
     *
     * @param filePaths 批量下载的文件路径
     * @param response
     * @throws IOException
     */
    public static void downloadZipFile(String prefix,List<File> filePaths, String zipName, HttpServletResponse response) throws IOException {
        byte[] data = ZipFileUtil.zip(prefix,filePaths);
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((zipName + ".zip").getBytes(), StandardCharsets.UTF_8));
        FileWriterUtil.writeByteToOutputStream(data, response.getOutputStream());
    }

    //将所有需要下载的文件以压缩包形式转换成base64字符串
    public static String downloadZipFileToBase64(String prefix,List<File> filePaths) throws IOException {
        byte[] zip1 = ZipFileUtil.zip(prefix,filePaths);
        return Base64.getEncoder().encodeToString(zip1);
    }

    //将目录下所有需要下载的文件以压缩包形式转换成base64字符串
    public static String downloadDirZipFileToBase64(String prefix,String dirPath) throws IOException {
        byte[] zip1 = ZipFileUtil.zipDir(prefix,new File(dirPath));
        return Base64.getEncoder().encodeToString(zip1);
    }


    /**
     * 下载网络文件给游览器
     *
     * @param urlpath  下载地址
     * @param response
     * @throws MalformedURLException
     */
    public static void downloadNet(String urlpath, HttpServletResponse response) throws MalformedURLException {
        URL url = new URL(urlpath);
        try (
                ServletOutputStream outputStream = response.getOutputStream();
                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                ByteArrayOutputStream output = new ByteArrayOutputStream();
        ) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context = output.toByteArray();
            String file = url.getFile();
            file = file.substring(file.lastIndexOf("/") + 1, file.length());
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" +  URLEncoder.encode(file, "UTF-8"));//展示给用户的

            outputStream.write(context);
        } catch (IOException e) {
            throw new BizException(e, "文件下载失败");
        }
    }


    /**
     * 下载字符串到文件里给游览器
     *
     * @param str      字符串内容
     * @param fileName 文件内容
     * @param response
     */
    public static void downloadStr(String str, String fileName, HttpServletResponse response) {
        try (
                OutputStream os = response.getOutputStream();
        ) {
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(), StandardCharsets.UTF_8));
            byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
            // 将字节流传入到响应流里,响应到浏览器
            os.write(bytes);
        } catch (Exception ex) {
            throw new BizException(ex, "文件下载失败");
        }
    }




}
